
_ = require 'underscore'
ViewContentHandler = require '../helpers/view_content_handler'
HttpHandler = require '../../../helpers/http_handler'
ViewDataHandler = require '../models/view_data_handler'
ImageHandle = require '../../../utils/image_handle'

###*
 * [homePageHandle description]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
###
homePageHandle = (req, res, next) ->
  params = req.params
  currentPage = global.parseInt params.page || 1
  tag = params.tag
  title = req.query.title
  eachPageTotal = 30
  options = 
    # sort : 'modifiedTime'
    sort : 
      modifiedTime : 'desc'
    limit : eachPageTotal
    skip : eachPageTotal * (currentPage - 1)
  if tag
    query = 
      tags : 
        $all : [
          tag
        ]
  else if title
    query = 
      title : title
  else
    query = {}

  ViewDataHandler.home query, options, (err, results) ->
    if err
      res.render 'error', 504
    else
      pageConfig =
        currentPage : currentPage
        eachPageTotal : eachPageTotal
        total : results.total
      view = 'ys/home'
      renderData = ViewContentHandler.home req, view, '每天浏览一下，关注更多的新产品！', 0, results.data, pageConfig, tag
      HttpHandler.renderAndCache req, res, view, renderData

      # picList = []
      # _.each results.data, (item) ->
      #   if _.isArray item.pics
      #     _.each item.pics, (pic) ->
      #       picList.push pic.url

      # imageHandle = new ImageHandle()
      # imageHandle.downloadImages picList


module.exports = homePageHandle
